package com.retail.lottery.colalottery.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.retail.lottery.colalottery.constant.RedisConstant;
import com.retail.lottery.colalottery.entity.CustomerAgreementInfo;
import com.retail.lottery.colalottery.enums.DeleteStatusEnum;
import com.retail.lottery.colalottery.service.CustomerAgreementInfoService;
import com.retail.lottery.colalottery.mapper.CustomerAgreementInfoMapper;
import com.retail.lottery.colalottery.service.WechatCustomerService;
import com.retail.lottery.colalottery.vo.ResultVO;
import com.retail.lottery.colalottery.vo.request.CustomerAgreementRequest;
import com.retail.lottery.colalottery.vo.request.SaveUserInfoRequest;
import io.micrometer.core.instrument.util.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.compress.utils.Lists;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @author jarvis.zhang
 * @description 针对表【customer_agreement_info(客户授权小程序协议签署表)】的数据库操作Service实现
 * @createDate 2025-06-12 10:21:11
 */
@Service
@Slf4j
public class CustomerAgreementInfoServiceImpl extends ServiceImpl<CustomerAgreementInfoMapper, CustomerAgreementInfo>
        implements CustomerAgreementInfoService {

    @Resource
    private WechatCustomerService wechatCustomerService;
    @Resource
    private RedisTemplate redisTemplate;

    @Override
    public ResultVO<?> agreement(CustomerAgreementRequest request) {
        //授权时候需要再更新客户信息  要看流程
        //查询当前是否有客户信息，没有的话 保存客户信息
        wechatCustomerService.userInfoSaveOrUpdate(changeRequestToWechatCustomer(request));

        CustomerAgreementInfo agreementInfo = new CustomerAgreementInfo();
        List<CustomerAgreementInfo> agreementInfos = baseMapper.selectList(new LambdaQueryWrapper<CustomerAgreementInfo>()
                .eq(CustomerAgreementInfo::getBuCode, request.getBuCode())
                .eq(CustomerAgreementInfo::getSetupId, request.getSetupId())
                .eq(CustomerAgreementInfo::getOpenId, request.getOpenId())
                .eq(ObjectUtil.isNotEmpty(request.getOneid()), CustomerAgreementInfo::getOneid, request.getOneid())
                .eq(CustomerAgreementInfo::getIsDel, DeleteStatusEnum.no_del.getCode()));

        if (CollectionUtil.isNotEmpty(agreementInfos)) {
            for (CustomerAgreementInfo info : agreementInfos) {
                BeanUtils.copyProperties(request, info);
                info.setUpdateTime(new Date());
            }
            this.updateBatchById(agreementInfos);
        } else {
            BeanUtils.copyProperties(request, agreementInfo);
            agreementInfo.setUpdateTime(new Date());
            this.save(agreementInfo);
            agreementInfos.add(agreementInfo);
        }
        redisTemplate.opsForValue().set(String.format(RedisConstant.REDIS_KEY_USER_INFO_TOKEN
                        , request.getSetupId(), request.getOpenId(), request.getOneid()),
                JSONObject.toJSONString(agreementInfos), 5, TimeUnit.MINUTES);
        return ResultVO.succ(Boolean.TRUE);
    }

    private SaveUserInfoRequest changeRequestToWechatCustomer(CustomerAgreementRequest request) {
        log.info("授权阶段用户信息,请求参数:{}", request);
        SaveUserInfoRequest saveUserInfoRequest = new SaveUserInfoRequest();
        saveUserInfoRequest.setOpenId(request.getOpenId());
        saveUserInfoRequest.setOneid(request.getOneid());
        saveUserInfoRequest.setEncryptMobile(request.getEncryptMobile());
        saveUserInfoRequest.setUnionId(request.getUnionId());
        saveUserInfoRequest.setNickName(request.getNickName());
        saveUserInfoRequest.setAvatarUrl(request.getAvatarUrl());
        saveUserInfoRequest.setStatus(request.getStatus());
        saveUserInfoRequest.setMobile(request.getMobile());
        saveUserInfoRequest.setCustomerId(request.getCustomerId());
        saveUserInfoRequest.setAgreementTime(request.getAgreementTime());
        saveUserInfoRequest.setAgreementInfo(request.getAgreementInfo());
        return saveUserInfoRequest;
    }

    @Override
    public ResultVO<?> queryAgreement(CustomerAgreementRequest request) {
        log.info("查询授权信息,请求参数:{}", request);
        Object agreementCache = redisTemplate.opsForValue().get(String.format(RedisConstant.REDIS_KEY_USER_INFO_TOKEN
                , request.getSetupId(), request.getOpenId(), request.getOneid()));
        if (Objects.nonNull(agreementCache) &&
                agreementCache instanceof String &&
                CollectionUtils.isNotEmpty(JSONObject.parseArray(agreementCache.toString(), CustomerAgreementInfo.class))) {
            return ResultVO.succ(JSONObject.parseArray(agreementCache.toString(), CustomerAgreementInfo.class));
        }

        List<CustomerAgreementInfo> agreementInfos = baseMapper.selectList(new LambdaQueryWrapper<CustomerAgreementInfo>()
                .eq(CustomerAgreementInfo::getBuCode, request.getBuCode())
                .eq(CustomerAgreementInfo::getSetupId, request.getSetupId())
                .eq(CustomerAgreementInfo::getOpenId, request.getOpenId())
                .eq(CustomerAgreementInfo::getIsDel, DeleteStatusEnum.no_del.getCode()));

        List<CustomerAgreementInfo> newUserAgreementList = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(agreementInfos)) {
            for (CustomerAgreementInfo agreementInfo : agreementInfos) {
                if (StringUtils.isNotBlank(request.getOneid())) {
                    if (StringUtils.isNotBlank(agreementInfo.getOneid())) {
                        if (agreementInfo.getOneid().equals(request.getOneid())) {
                            newUserAgreementList.add(agreementInfo);
                        } else {
                            // oneid不一致表示当前用户为历史注销的用户，该协议不能使用
                            continue;
                        }
                    } else {
                        // 因为第一个版本的问题，导致第一个版本的协议上没有全渠道会员id，发现为空补全渠道会员id信息
                        agreementInfo.setOneid(request.getOneid());
                        baseMapper.updateById(agreementInfo);
                        newUserAgreementList.add(agreementInfo);
                    }
                } else {
                    newUserAgreementList.add(agreementInfo);
                }
            }
            redisTemplate.opsForValue().set(String.format(RedisConstant.REDIS_KEY_USER_INFO_TOKEN
                            , request.getSetupId(), request.getOpenId(), request.getOneid()),
                    JSONObject.toJSONString(newUserAgreementList), 5, TimeUnit.MINUTES);
        }

        return ResultVO.succ(
                CollectionUtils.isEmpty(newUserAgreementList)
                        ? Lists.newArrayList()
                        : newUserAgreementList.stream().distinct().collect(Collectors.toList()));
    }
}




